import { login, getUserInfo, getUserDetail } from '@/api/user'
import { resetRouter } from '@/router'
// 使用cookie保存token，利用已经封装的函数
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  // token: localStorage.getItem('hrToken-69') || ''
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    // localStorage.setItem('hrToken-69', data)
    setToken(data)
    state.token = data
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    console.log('vuex', res)
    if (res) {
      store.commit('setToken', res)
    }
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const detail = await getUserDetail(res.userId)
    const obj = { ...res, ...detail }
    store.commit('setUserInfo', obj)
    // store.commit('setUserInfo', res)
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    // 退出登录后清理路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

